package com.yyf.blogapi.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yyf.blogapi.po.SysUser;
import com.yyf.blogapi.service.ISysUserService;
import com.yyf.blogapi.util.JwtUtil;
import com.yyf.blogapi.util.UserThreadLocal;
import com.yyf.blogapi.common.ErrorCode;
import com.yyf.blogapi.vo.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class NeedLoginInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;
    @Resource
    ISysUserService sysUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        log.info("request uri   : {}",request.getRequestURI());
        log.info("request method: {}",request.getMethod());
        log.info("token         : {}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)){
            Result fail = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(fail));
            return false;
        }

        //验证token
        Claims claims = jwtUtil.getClaims(token);
        SysUser user = sysUserService.checkToken(token);
        if (user==null){
            Result fail = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(fail));
            return false;
        }

        //登录验证成功，放行
        //我希望在controller中 直接获取用户的信息 怎么获取?
        //必须通过此拦截，说明确实已经登录了，才把user信息放到UserThreadLocal中
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
